$.canui('dialog', {
    options: {
        autoOpen: false,
        buttons: [],
        closeOnEscape: false,//按esc是否关闭窗口
        draggable: true,
        show: null,
        hide: null,
        height: "auto",
        maxHeight: null,
        maxWidth: null,
        minHeight: 185,
        minWidth: 250,
        type: 'normal',//normal、message

        resizable: true,
        title: null,
        width: 300,

        beforeClose: null,
        close: null,
        open: null
    },
    overlay: null,
    _dialog: null,
    _create: function () {
        var _t = this;

        if (_t.element.parent()[0].tagName !== 'BODY') {
            _t.element.appendTo($('body'));
        }

        //if (_t.options.height) {
        //    _t.element.height(_t.options.height - 140);
        //}

        if (_t.element[0].tagName === 'IFRAME') {
            //_t.element.height(_t.options.height - 115);
            _t.element.wrap('<div class="pop-bd" style="padding: 0;overflow: hidden;"></div>');
        } else {
            _t.element.wrap('<div class="pop-bd"></div>');
        }
        _t.element.parent().wrap('<div class="pop"></div>');

        _t._dialog = _t.element.parent().parent();

        _t._createTitleBar();
        _t._createBottomBar();

        var titleHeight = 38;
        var bottomHeight = _t.options.buttons.length ? 77 : 0;
        if (_t.element[0].tagName === 'IFRAME') {//节点为iframe时，该节点没有加上padding 25px 20px 0;样式
            _t.element.height(_t.options.height - titleHeight - bottomHeight);
        } else {
            _t.element.height(_t.options.height - titleHeight - bottomHeight - 25);//额外需要再减去padding-top的值
        }

        if (_t.options.resizable) {
            _t._dialog.resizable({
                cancel: ".pop-bd",
                containment: "document",
                alsoResize: _t.element,
                maxWidth: _t.options.maxWidth,
                maxHeight: _t.options.maxHeight,
                minWidth: _t.options.minWidth,
                minHeight: _t.options.minHeight,
                handles: "n,e,s,w,se,sw,ne,nw"
            })
        }
    },
    _init: function () {
        var _t = this;
        _t.element.show();
        if (_t.options.autoOpen) {
            _t.open();
        }

        _t._dialog.css({
            left: ($(window).width() - _t.options.width) / 2,
            top: ($(window).height() - _t._dialog.height()) / 2,
            width: _t.options.width,
            height: _t.options.height
        });
    },
    _isOpen: false,
    open: function () {
        var _t = this;
        if (_t.isOpen) {
            _t._moveToTop();
            _t.overlay.insertBefore(_t._dialog);
            return;
        }
        _t.isOpen = true;
        _t._moveToTop();
        _t._dialog.show();
        _t._createOverlay();
        return _t.element;
    },
    setOptions: function (obj) {
        var _t = this;
        for (var prop in obj) {
            _t.setOption(prop, obj[prop]);
        }
        return _t.element;
    },
    setOption: function (name, val) {
        var _t = this;
        var $btns;
        switch (name) {
            case 'title':
                _t.element.parent().prev().find('h3').text(val || '');
                break;
            case 'hideBtn':
                $btns = _t.element.parent().next().find('a').show();
                $.each(val, function (i, d) {
                    $btns.eq(d).hide();
                });
                break;
            case 'showBtn':
                $btns = _t.element.parent().next().find('a').hide();
                $.each(val, function (i, d) {
                    $btns.eq(d).show();
                });
                break;
        }
        return _t.element;
    },
    _moveToTop: function () {
        var _t = this;
        var prev = _t._dialog.nextAll('.pop:visible');
        if (prev.length) {
            _t._dialog.insertAfter(prev.get(0));
        }
    },
    close: function () {
        var _t = this;
        _t._destroyOverlay();
        _t._dialog.hide();
        _t.isOpen = false;

        if (_t.options.close) {
            _t.options.close.call(_t.element);
        }
        return _t.element;
    },
    _createTitleBar: function () {
        var _t = this;
        var $titile = $('<div class="title-bar"></div>');
        $titile.append('<h3>' + (_t.options.title || '') + '</h3>');
        var $close = $('<a class="close-btn"></a>').appendTo($titile);
        $close.on('click', function () {
            _t.close();
        });

        $titile.insertBefore(_t.element.parent());
        if (_t.options.draggable) {
            $titile.css('cursor', 'move');
            _t._dialog.draggable({
                cancel: ".pop-bd, .close-btn",
                handle: ".title-bar",
                containment: "document"
            });
        }
    },
    _createBottomBar: function () {
        var _t = this;
        if (!_t.options.buttons.length) {
            return;
        }
        var $bottom = $('<div class="btn-box"></div>');

        $.each(_t.options.buttons, function (index, item) {
            var button = $('<a class="btn ' + (item.css || 'btn-cancel') + '">' + item.text + '</a>').appendTo($bottom);
            button.on('click', function () {
                item.click.apply(_t.element[0], arguments);
            });
        });

        $bottom.insertAfter(_t.element.parent());
    },

    _createOverlay: function () {
        this.overlay = $("<div>").addClass("shadow-layer").insertBefore(this._dialog);
    },
    _destroyOverlay: function () {
        if (this.overlay) {
            this.overlay.remove();
            this.overlay = null;
        }
    },
    destroy: function () {
        this._dialog.remove();
        this._destroyOverlay();
    },
    /**
     * 执行对象中iframe对应的方法
     * @param fnName
     */
    exec: function (fnName) {
        var args = $.makeArray(arguments).slice(1);
        var argArr = [this.element[0], fnName];
        $.each(args, function (i, data) {
            argArr.push(data);
        });
        return $.execIframeFn.apply(this, argArr);
    }
});

/**************************************
 *消息弹出窗口
 *
 ***************************************/
(function ($) {
    $.messager = {
        /**
         *基本弹出窗口
         * @param title {String} 标题
         * @param msg {String} 提示信息
         * @param type {String} 提示类型【error、info、success、warning】
         * @param callback {Function} 点击确定按钮后回调函数
         */
        alert: function (title, msg, type, callback) {
            type = type || 'info';
            var css = 'icon-warning';
            switch (type) {
                case "error":
                    css = "pop-icon-alert";
                    break;
                case "success":
                    css = "pop-icon-success";
                    break;
            }

            var contentHtml = '<div class="warning-title"><span class="icon {0}"></span>{1}</div>'.format(css, msg);

            var defaultWidth = 420;

            $('<div>' + contentHtml + '</div>').appendTo('body').dialog({
                title: title || '系统提示',
                autoOpen: true,
                draggable: false,
                width: defaultWidth,
                resizable: false,
                modal: true,
                close: function () {
                    $(this).dialog('destroy');
                },
                buttons: [
                    {
                        text: '关闭',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('close');
                            if (callback) {
                                callback();
                            }
                        }
                    }
                ]
            });
        },
        /**
         * 询问弹出框
         * @param title {String} 标题
         * @param msg (String) 询问信息
         * @param type {String} 提示类型 type为delete时是删除图标，否则就是询问图标
         * @param callback {Function} 点击按钮回调函数，true为点击了确定按钮，false为点击了取消了按钮
         */
        confirm: function (title, msg, type, callback) {
            var defaultWidth = 420;
            if (typeof type === 'function') {
                callback = type;
                type = '';
            }

            var $div = $('<div class="warning-title"><span class="icon {0}"></span>{1}</div>'.format(type === 'delete' ? 'pop-icon-delete' : 'pop-icon-ask', msg));
            $div.appendTo('body').dialog({
                title: title || '系统提示',
                autoOpen: true,
                draggable: false,
                width: defaultWidth,
                resizable: false,
                modal: true,
                close: function () {
                    $(this).dialog('destroy');
                },
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            $(this).dialog('close');
                            if (callback) {
                                callback(true);
                            }
                        }
                    },
                    {
                        text: '取消',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('close');
                            if (callback) {
                                callback(false);
                            }
                        }
                    }
                ]
            });
        }
    };
})(jQuery);

//树形结构数据（弹出框）
(function ($) {
    var treeDialog, $dialog = null, // 树形对话框
        treeDataCache = {},//树数据缓存
        $treeObj = null,//树jQuery对象
        treeId = 'tree-treeDialog',//树ID
        optionsJSON = null,//配置信息JSON
        callback = null,//回调函数
        checkable = true;//是否多选

    var $obj;
    var context;//上下文

    /**
     * 从后台读取树形结构所需要的数据
     */
    function loadLeftTreeData() {
        $.ajaxExt({
            url: optionsJSON.url,
            type: 'POST',
            dataType: 'JSON',
            success: function (result) {
                createLeftTree(result || []);
            }
        });
    }

    /**
     * 根据配置信息创建树
     */
    function createLeftTree(data) {

        if (!data.length) {
            $treeObj.empty().append('无数据，请联系管理员！');
        } else {
            var setting = {
                view: {
                    showIcon: true,
                    selectedMulti: false
                },
                data: {
                    key: {
                        name: optionsJSON.name
                    },
                    simpleData: {
                        enable: true,
                        idKey: optionsJSON.idKey,
                        pIdKey: optionsJSON.pIdKey,
                        rootPId: 0
                    }
                },
                check: {
                    enable: false,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "s", "N": "ps"}
                }
            };

            //$.fn.zTree.init($treeObj, setting, data);
            //var treeObj = $.fn.zTree.getZTreeObj(treeId);
            $treeObj.createTree(setting, data, {search: $('.search-area :text', $dialog)}).expandAll(true);
            //treeObj.expandAll(true);
        }
    }

    /**
     * 选择完节点后点击确定触发相应的事件（包含填充对应的值）
     * @returns {boolean}
     */
    function fireEvent() {
        var treeObj = $.fn.zTree.getZTreeObj(treeId),
            nodes;
        nodes = treeObj.getSelectedNodes();

        if (nodes.length) {
            $obj.val(nodes[0][optionsJSON.name]).siblings('input:hidden').val(nodes[0][optionsJSON.idKey]);
            if (optionsJSON.cascade) {
                cascade(nodes[0][optionsJSON.idKey]);
            }
            callback && callback(nodes[0]);
        } else {
            $.messager.alert('信息', '未选中一条记录！');
            return false;
        }
        return true;
    }

    /**
     * 级联操作,相对应的控件进行清值、重新加载数据的操作
     */
    function cascade(val) {
        var cascadeIds = optionsJSON.cascade.split(',');

        //var body = $obj.closest('body');
        for (var i = 0, len = cascadeIds.length; i < len; i++) {
            var _$t = context.$.find('#' + cascadeIds[i]),
                _options = context.$.fn.getOptions.call(_$t);
            if (_$t[0].attributes['user-type'] === 'treeDialog') {//如果要级联的控件也是树形弹出框的控件

            } else if (_$t[0].tagName === 'SELECT') {
                if (_options.param) {
                    var params = {};
                    params[_options.param] = val;
                    _options.params = params;
                }
                context.$.fn._select2Load.call(_$t, _options);
                //_$t._select2Load(_options);
            }
        }
    }


    treeDialog = function (options, obj, _callback) {
        $obj = $(obj);
        callback = _callback;
        if (typeof options === "object") {
            optionsJSON = options;
        } else {
            optionsJSON = (new Function('return ' + options))();
        }

        if (!optionsJSON.url) {
            return;
        }
        context = this;
        if (!$dialog) {
            var html = '<div class="tree-pop">' +
                '<div class="search-area">' +
                '<div class="tip"><span class="icon-search"></span>搜索</div>' +
                '<input type="text">' +
                '</div>' +
                '<div class="tree-area"><ul class="ztree" style="overflow: auto;height:351px;" id="' + treeId + '"></ul></div>' +
                '</div>';
            $dialog = $(html).appendTo($('body')).dialog({
                title: '请选择',
                width: 345,
                height: 540,
                resizable: false,
                modal: true,
                close: function () {
                    context = null;
                    $('.search-area :text', this).val('').prev().show();
                },
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            if (fireEvent()) {
                                $(this).dialog('close');
                            }
                        }
                    },
                    {
                        text: '重置',
                        css: 'btn-cancel',
                        click: function () {
                            callback && callback();
                            $obj.val('').siblings(':hidden').val('');
                            $(this).dialog('close');
                        }
                    }
                ]
            });
            $('.tip', $dialog).on('click', function () {
                $(this).hide().next().focus();
            });
            $(':text', $dialog).on('click', function () {
                $(this).prev().hide();
            }).on('blur', function () {
                if (!$(this).val()) {
                    $(this).prev().show();
                }
            });
            $treeObj = $('#' + treeId);
        }

        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        if (treeObj) {
            treeObj.destroy();
        }

        loadLeftTreeData();

        $dialog.dialog('open');
    };

    window.treeDialog = treeDialog;
})(jQuery);
